package com.nf.health.app.inquiry.docdetail;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.nf.health.app.AppModel;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.chatservice.activity.ChatActivity;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.VolleyErrorHelper;
import com.nf.health.app.inquiry.adapter.DocDetailRecycleAdapter;
import com.nf.health.app.inquiry.bean.DoctorDetailBean;
import com.nf.health.app.models.BaseBean;
import com.nf.health.app.models.DoctorCommnetVo;
import com.nf.health.app.models.DoctorServiceSettingModel;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.widget.MyMainItemAnimation;
import com.nf.health.app.widget.OnMyOnClistener;
import com.nf.health.app.widget.OnMyOnClistener2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 医生详情主界面
 *
 * @author yyh
 * @date 2015-11-4 上午9:57:30
 */
public class DocDetailActivity extends BaseActivity {
    public final static String DOCTORID = "com.nf.doctorId";
    @Bind(R.id.swipe_doc_refresh_layout)
    SwipeRefreshLayout swipe_doc_refresh_layout;
    @Bind(R.id.recyclerView_docdatil)
    RecyclerView recyclerView_docdatil;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebar_title_tv;
    @Bind(R.id.btn_go_detail)
    Button btn_go_detail;
    @Bind(R.id.ll_bottom_detail_view)
    LinearLayout ll_bottom_detail_view;

    private DocDetailRecycleAdapter docDetailRecycleAdapter;
    private String pageNo = "1";
    private String pageSize = "3";
    private String doctorId = "2016010816545959080910";
    private List<DoctorCommnetVo> doctorCommnetVoList;
    private List<DoctorServiceSettingModel> doctorServiceSettingModelList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_docdetailactivity);
        ButterKnife.bind(this);
        initView();
        loadBaseDocDetail();
    }

    private void initView() {
        btn_go_detail.setOnClickListener(this);
        swipe_doc_refresh_layout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        recyclerView_docdatil.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView_docdatil.setLayoutManager(mLayoutManager);
        recyclerView_docdatil.setItemAnimator(new MyMainItemAnimation());
        docDetailRecycleAdapter = new DocDetailRecycleAdapter(this, null);
        recyclerView_docdatil.setAdapter(docDetailRecycleAdapter);

        recyclerView_docdatil.addItemDecoration(new DividerListItemDecoration(DocDetailActivity.this, LinearLayoutManager.VERTICAL, 1,
                getResources().getColor(R.color.divider_line_color)));
        swipe_doc_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadBaseDocDetail();
            }
        });
        titlebar_title_tv.setText("医生详情");
        doctorId = getIntent().getStringExtra(DOCTORID);
        docDetailRecycleAdapter.regisitOnClickListener(new OnMyOnClistener() {
            @Override
            public void onMyClickCallBack() {
                Bundle bundle = new Bundle();
                bundle.putString(Constants.DOCTOR_ID, doctorId);
                ActivityUtils.showActivity(DocDetailActivity.this, DocCommentDiscussActivity.class, bundle);//查看全部的的  评价列表
            }
        });
        docDetailRecycleAdapter.regisitOnMyOnClistener2(new OnMyOnClistener2() {////取消关注医生
            @Override
            public void onMyClickCallBack(String attention) {
                if (!Util.isLogin()) {
                    ActivityUtils.showActivity(DocDetailActivity.this, LoginActivity.class);
                    return;
                }
                //   -1 不能关注, 0未关注，1已关注，2 不能取消关注
                if (attention.equals("0")) {//去关注
                    provider.addAttention(doctorId);
                } else if (attention.equals("1")) {//取消关注
                    provider.requestCancleFoucsDoctor(doctorId, Act.Flag.ATTATION_DELETE_DOCTOR_FLG);
                } else if (attention.equals("-1")) {//不能关注
                    provider.requestCancleFoucsDoctor(doctorId, Act.Flag.ATTATION_DELETE_DOCTOR_FLG);
                   // GetToast.useString(DocDetailActivity.this, "不能关注");
                } else if (attention.equals("2")) {//不能取消关注
                   // GetToast.useString(DocDetailActivity.this, "不能取消关注");
                    provider.requestCancleFoucsDoctor(doctorId, Act.Flag.ATTATION_DELETE_DOCTOR_FLG);
                }
            }
        });
    }

    private void loadBaseDocDetail() {
        ////**************provider.commitDoctorEvaluation(doctorId, 5+"", "请你告诉我爱上你是一个错，别让我失魂落魄着了魔", "asdfasdf");
        if (TextUtils.isEmpty(doctorId)) {
            GetToast.useString(DocDetailActivity.this, "参数不能为空！");
            return;
        }
        provider.requestDoctorDetail2(doctorId);//请求医生 详情
        provider.requestDoctorDetailComment2(pageNo + "", pageSize + "", doctorId, Act.Flag.DOC_DETAIL_COMMEMNT);//请求医生评论列表
        provider.getDoctorServiceSetting(doctorId);// 获取医生服务设置
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        swipe_doc_refresh_layout.setRefreshing(false);
        switch (actionName) {
            case Act.Flag.DOC_DETAIL:
                DoctorDetailBean doctorDetail = (DoctorDetailBean) object;
                docDetailRecycleAdapter.setMyHeaderDocDetail(doctorDetail);
                saveAsContact(doctorDetail);
                if(!TextUtils.isEmpty(doctorDetail.getDoctortype())){//医生类型，
                    if(doctorDetail.getDoctortype().equals("doctor")){//doctor普通医生
                        ll_bottom_detail_view.setVisibility(View.GONE);
                    }else if(doctorDetail.getDoctortype().equals("agent")){//agent助手
                        ll_bottom_detail_view.setVisibility(View.VISIBLE);
                    }else if(doctorDetail.getDoctortype().equals("organization")){//organization银行
                        ll_bottom_detail_view.setVisibility(View.GONE);
                    }
                }
                provider.getYlHospitalStatus(doctorDetail.getHid());// 获取挂号状态
                break;
            case Act.Flag.DOC_DETAIL_COMMEMNT:
                String totalCount = JsonUtils.getFiledData(object.toString(), "totalCount");
                String dataStr = JsonUtils.getFiledData(object.toString(), "data");
                String list = JsonUtils.getFiledData(dataStr, "list");
                Gson gson2 = new MyGsonBuilder().createGson();
                doctorCommnetVoList = gson2.fromJson(list, new TypeToken<List<DoctorCommnetVo>>() {
                }.getType());
                Collections.reverse(doctorCommnetVoList);
                docDetailRecycleAdapter.setDoctorCommentData(doctorCommnetVoList);//刷新评论列表
                if (doctorCommnetVoList != null) {//刷新评论列表的显示个数
                    docDetailRecycleAdapter.setHeadCommentHead(TextUtils.isEmpty(totalCount) ? 0 : Integer.parseInt(totalCount));
                }
                break;
            case Act.Flag.ATTATION_DOCTOR_FLG://去关注医生
                provider.requestDoctorDetail2(doctorId);//请求接口去刷新
                break;
            case Act.Flag.ATTATION_DELETE_DOCTOR_FLG://取消关注医生
                provider.requestDoctorDetail2(doctorId);//请求接口去刷新
                break;
            case Act.Flag.GETDOCTORSERVICESETTING_FLG://购买服务 设置
                String familyDoctorServiceSettingStr = JsonUtils.getFiledData(object.toString(), "family");
                String peyMoneyDescriptDoctorServiceSettingStr = JsonUtils.getFiledData(object.toString(), "consult");
                String HeanthymanagerDoctorServiceSettingStr = JsonUtils.getFiledData(object.toString(), "sound");
                String HworkTimeListStr = JsonUtils.getFiledData(object.toString(), "hworktime");
                Gson gson = new MyGsonBuilder().createGson();
                DoctorServiceSettingModel familyDoctorServiceSetting = gson.fromJson(familyDoctorServiceSettingStr, new TypeToken<DoctorServiceSettingModel>() {
                }.getType());
                DoctorServiceSettingModel peyMoneyDescriptDoctorServiceSetting = gson.fromJson(peyMoneyDescriptDoctorServiceSettingStr, new TypeToken<DoctorServiceSettingModel>() {
                }.getType());
                DoctorServiceSettingModel heanthymanagerDoctorServiceSetting = gson.fromJson(HeanthymanagerDoctorServiceSettingStr, new TypeToken<DoctorServiceSettingModel>() {
                }.getType());
                List<HashMap<String, String>> HworkTimeList = null;
                if(!TextUtils.isEmpty(HworkTimeListStr)){
                    HworkTimeList = gson.fromJson(HworkTimeListStr, new TypeToken<List<HashMap<String, String>>>() {
                    }.getType());
                }else{
                    HworkTimeList = new ArrayList<>();
                }
                //String data = JsonUtils.getFiledData(object.toString(),"hworktime"); 医生工作的时间
                doctorServiceSettingModelList.clear();
                familyDoctorServiceSetting = (familyDoctorServiceSetting == null ? new DoctorServiceSettingModel() : familyDoctorServiceSetting);
                peyMoneyDescriptDoctorServiceSetting = (peyMoneyDescriptDoctorServiceSetting == null ? new DoctorServiceSettingModel() : peyMoneyDescriptDoctorServiceSetting);
                heanthymanagerDoctorServiceSetting = (heanthymanagerDoctorServiceSetting == null ? new DoctorServiceSettingModel() : heanthymanagerDoctorServiceSetting);
                familyDoctorServiceSetting.setDoctorId(doctorId);
                peyMoneyDescriptDoctorServiceSetting.setDoctorId(doctorId);
                heanthymanagerDoctorServiceSetting.setDoctorId(doctorId);
                doctorServiceSettingModelList.add(familyDoctorServiceSetting);
                doctorServiceSettingModelList.add(peyMoneyDescriptDoctorServiceSetting);
                doctorServiceSettingModelList.add(heanthymanagerDoctorServiceSetting);
                docDetailRecycleAdapter.setDocFunctionData(doctorServiceSettingModelList);
                docDetailRecycleAdapter.seHworkTimeList(HworkTimeList);
                docDetailRecycleAdapter.notifyDataSetChanged();
                break;
            case Act.Flag.FLAG_HAS_NO_GHJL_STATUS://挂号记录
                String flag = (String) object;
                docDetailRecycleAdapter.setlRegistrationState(flag);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
       switch (v.getId()){
           case R.id.btn_go_detail:
               //咨询跳转到chatactivity
               Bundle bundle = new Bundle();
               bundle.putString(EaseConstant.EXTRA_USER_ID, doctorId);
               bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
               bundle.putString(ChatActivity.EXTRA_DOCTOR_TYPE, "40_");
               ActivityUtils.showActivity(DocDetailActivity.this, ChatActivity.class, bundle);
               break;
       }
    }

    /**
     *作为联系人存储起来
     * @param doctorDetail
     */
    private void saveAsContact(DoctorDetailBean doctorDetail) {
        EaseUser user = new EaseUser(doctorId);
        user.setNick(doctorDetail.getDoctorname());
        user.setAvatar(doctorDetail.getDoctorhimg());
        AppModel.getInstatnce().saveContact(user);
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        if(actionName.equals(Act.Flag.ATTATION_DOCTOR_FLG) || actionName.equals(Act.Flag.ATTATION_DELETE_DOCTOR_FLG)){
            if (TextUtils.isEmpty(response)) {
                //处理error
                showToast(VolleyErrorHelper.getMessage(error));
            } else {
                //处理response
                String code = JsonUtils.getKey2Value(response, "code");
                if ("2002".equals(code)) {
                    PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
                    //未登录
                    ActivityUtils.skipActivity(this, LoginActivity.class);
                } else {
                    try {
                        BaseBean bean = new Gson().fromJson(response, BaseBean.class);
                        if (TextUtils.isEmpty(bean.getMsg())) {
                            showToast("数据为空");
                        } else {
                            showToast(bean.getMsg());
                        }
                    } catch (Exception e) {
                        showToast(response);
                    }
                }
            }
        }else{
            super.handleActionError(actionName, response, error);
        }
        switch (actionName) {
            case Act.Flag.DOC_DETAIL:
                break;
            case Act.Flag.DOC_DETAIL_COMMEMNT:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
